package com.glo.quiki.req;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.glo.quiki.model.QuikiPaymentOrder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

public class QuikiParseHtml {

	public static List<QuikiPaymentOrder> parseTransactions(String html) {
		List<QuikiPaymentOrder> transactions = new ArrayList<>();
		Document doc = Jsoup.parse(html);
		Elements rows = doc.select("table tbody tr");

		ObjectMapper objectMapper = new ObjectMapper(); // 用于解析 JSON

		for (Element row : rows) {
			Elements cols = row.select("td");
			if (cols.size() >= 6) {
				String status = cols.get(1).text();
				String detail = cols.get(2).text();
				String amount = cols.get(3).text();
				String reference = cols.get(4).text();
				String date = cols.get(5).text();
				String performedBy = cols.size() > 6 ? cols.get(6).text() : "";

				// 查找按钮，提取 `data-value`
				Element button = cols.get(0).selectFirst("button");
				String transactionId = null, owner = null, account = null, taxId = null;
				String transactionType = null, provider = null, externalId = null;

				if (button != null) {
					String dataValue = button.attr("data-value");

					try {
						JsonNode jsonNode = objectMapper.readTree(dataValue);
						transactionId = jsonNode.path("id").asText();
						owner = jsonNode.path("osOwner").asText();
						account = jsonNode.path("osAccount").asText();
						taxId = jsonNode.path("osTaxId").asText();
						transactionType = jsonNode.path("type").asText();
						provider = jsonNode.path("provider_name").asText();
						externalId = jsonNode.path("external_transaction_id").asText();
					} catch (Exception e) {
						System.err.println("JSON 解析失败: " + e.getMessage());
					}
				}

				// 使用 Builder 创建对象
				QuikiPaymentOrder order = QuikiPaymentOrder.builder()
					.status(status)
					.detail(detail)
					.amount(amount)
					.reference(reference)
					.date(date)
					.performedBy(performedBy)
					.transactionId(transactionId)
					.owner(owner)
					.account(account)
					.taxId(taxId)
					.transactionType(transactionType)
					.provider(provider)
					.externalId(externalId)
					.build();

				transactions.add(order);
			}
		}
		return transactions;
	}

}
